package com.xiaoshuidi.cloud.module.finance.service.voucher.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.module.contract.api.ContractRentOrderApi;
import com.xiaoshuidi.cloud.module.finance.controller.admin.voucher.vo.FinanceVoucherDetailRespVO;
import com.xiaoshuidi.cloud.module.finance.controller.admin.voucher.vo.FinanceVoucherInfoSearchReqVO;
import com.xiaoshuidi.cloud.module.finance.convert.voucher.FinanceVoucherDetailConvert;
import com.xiaoshuidi.cloud.module.finance.dal.dataobject.voucher.FinanceVoucherDetailDO;
import com.xiaoshuidi.cloud.module.finance.dal.dataobject.voucher.FinanceVoucherInfoDO;
import com.xiaoshuidi.cloud.module.finance.dal.mysql.certificate.FinanceCertificateConfigMapper;
import com.xiaoshuidi.cloud.module.finance.dal.mysql.voucher.FinanceVoucherDetailMapper;
import com.xiaoshuidi.cloud.module.finance.dal.mysql.voucher.FinanceVoucherInfoMapper;
import com.xiaoshuidi.cloud.module.finance.enums.voucher.FinanceVoucherJieDaiTypeEnum;
import com.xiaoshuidi.cloud.module.finance.enums.voucher.FinanceVoucherStatusEnum;
import com.xiaoshuidi.cloud.module.finance.enums.voucher.FinanceVoucherTypeEnum;
import com.xiaoshuidi.cloud.module.finance.kdclient.WSContext;
import com.xiaoshuidi.cloud.module.finance.kdclient.WSWSVoucher;
import com.xiaoshuidi.cloud.module.finance.service.voucher.FinanceVoucherService;
import com.xiaoshuidi.cloud.module.finance.util.KingdeeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
	* @author dujianguang
	*/
@Service
@Slf4j
public class FinanceVoucherServiceImpl implements FinanceVoucherService {
	@Resource
	private ContractRentOrderApi contractRentOrderApi;
	@Resource
	private FinanceVoucherInfoMapper financeVoucherInfoMapper;
	@Resource
	private FinanceVoucherDetailMapper financeVoucherDetailMapper;
	@Resource
	private FinanceCertificateConfigMapper financeCertificateConfigMapper;

	@Override
	@TenantIgnore
	public PageResult<FinanceVoucherInfoDO> getInfoPage(FinanceVoucherInfoSearchReqVO pageVO) {
		return financeVoucherInfoMapper.selectPage(pageVO);
	}

	@Override
	@TenantIgnore
	public List<FinanceVoucherDetailRespVO> getDetail(Long voucherId) {
		LambdaQueryWrapper<FinanceVoucherDetailDO> query = Wrappers.lambdaQuery();
		query.eq(FinanceVoucherDetailDO::getVoucherId, voucherId);
		query.orderByAsc(FinanceVoucherDetailDO::getSeq);
		List<FinanceVoucherDetailDO> financeVoucherDetailDOS = financeVoucherDetailMapper.selectList(query);
		return FinanceVoucherDetailConvert.INSTANCE.convert(financeVoucherDetailDOS);
	}

	@Override
	@TenantIgnore
	public String syncVoucher(Long voucherId) {
		LambdaQueryWrapper<FinanceVoucherInfoDO> infoQuery = Wrappers.lambdaQuery();
		infoQuery.eq(FinanceVoucherInfoDO::getId, voucherId);
		FinanceVoucherInfoDO voucherInfoDO = financeVoucherInfoMapper.selectOne(infoQuery);

		LambdaQueryWrapper<FinanceVoucherDetailDO> detailQuery = Wrappers.lambdaQuery();
		detailQuery.eq(FinanceVoucherDetailDO::getVoucherId, voucherId);
		List<FinanceVoucherDetailDO> detailDOList = financeVoucherDetailMapper.selectList(detailQuery);

		List<WSWSVoucher> wswsVouchers = jieVouchersConvert(voucherInfoDO, detailDOList);
		WSContext wsContext = KingdeeUtil.easLogin();
		System.out.println("userName：" + wsContext.getUserName() + "；sessionId：" + wsContext.getSessionId());
		WSWSVoucher[] arrs = wswsVouchers.stream().toArray(WSWSVoucher[]::new);
		log.info("userName：" + wsContext.getUserName() + "；sessionId：" + wsContext.getSessionId());
		log.info("arrs{}", JSON.toJSONString(arrs));
		String[] result = KingdeeUtil.importVoucher(wsContext.getSessionId(), arrs);
		if (result[4].equals("0000")) {
			String kdNo = result[6];
			LambdaUpdateWrapper<FinanceVoucherInfoDO> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.eq(FinanceVoucherInfoDO::getId, voucherId);
			updateWrapper.set(FinanceVoucherInfoDO::getKdNo, kdNo);
			updateWrapper.set(FinanceVoucherInfoDO::getStatus, FinanceVoucherStatusEnum.VOUCHER_STATUS_SUCCESS.getCode());
			financeVoucherInfoMapper.update(null, updateWrapper);
			return result[5];
		} else {
			return result[5];
		}

	}

	@Override
	public String job() {
		return null;
	}

	//分装金蝶请求凭证头--借方
	private static List<WSWSVoucher> jieVouchersConvert(FinanceVoucherInfoDO voucherInfoDO, List<FinanceVoucherDetailDO> detailDOList) {
		List<WSWSVoucher> list = detailDOList.stream().map(entity -> {
			WSWSVoucher wswsVoucher = new WSWSVoucher();
			//凭证头
			wswsVoucher.setCompanyNumber(voucherInfoDO.getCompanyCode());
			wswsVoucher.setBookedDate(voucherInfoDO.getBookTime());
			wswsVoucher.setBizDate(voucherInfoDO.getBusinessTime());
			wswsVoucher.setPeriodYear(Integer.valueOf(voucherInfoDO.getAnnual()));
			wswsVoucher.setPeriodNumber(Integer.valueOf(voucherInfoDO.getAnnualCode()));
			wswsVoucher.setVoucherType(FinanceVoucherTypeEnum.find(voucherInfoDO.getVoucherType()).getName());
			wswsVoucher.setVoucherNumber(voucherInfoDO.getSeqNo());

			//分录行
			wswsVoucher.setEntrySeq(entity.getSeq());
			wswsVoucher.setAccountNumber(entity.getAccountNumber());
			wswsVoucher.setVoucherAbstract(entity.getVoucherAbstract());
			wswsVoucher.setCurrencyNumber("BB01");
			wswsVoucher.setEntryDC(entity.getEntryDc());
			wswsVoucher.setOriginalAmount(entity.getOriginalAmount().doubleValue());
			if (FinanceVoucherJieDaiTypeEnum.JIE.getCode().equals(entity.getEntryDc())) {
				wswsVoucher.setDebitAmount(entity.getOriginalAmount().doubleValue());
			} else {
				wswsVoucher.setCreditAmount(entity.getDebitAmount().doubleValue());
			}

			wswsVoucher.setCreator(voucherInfoDO.getMakeBy());


			// 辅助账
			if (StringUtils.isNotEmpty(entity.getAccountProject1())) {
				wswsVoucher.setAsstSeq(1);
				wswsVoucher.setAsstActType1(entity.getAccountProject1());
				wswsVoucher.setAsstActNumber1(entity.getAccountProjectCode1());
				wswsVoucher.setAsstActName1(entity.getAccountProjectName1());
			}
			if (StringUtils.isNotEmpty(entity.getAccountProject2())) {
				wswsVoucher.setAsstSeq(2);
				wswsVoucher.setAsstActType2(entity.getAccountProject2());
				wswsVoucher.setAsstActNumber2(entity.getAccountProjectCode2());
				wswsVoucher.setAsstActName2(entity.getAccountProjectName2());
			}
			if (StringUtils.isNotEmpty(entity.getAccountProject3())) {
				wswsVoucher.setAsstSeq(3);
				wswsVoucher.setAsstActType3(entity.getAccountProject3());
				wswsVoucher.setAsstActNumber3(entity.getAccountProjectCode3());
				wswsVoucher.setAsstActName3(entity.getAccountProjectName3());
			}


			return wswsVoucher;
		}).collect(Collectors.toList());
		return list;
	}



}
